<template>
  <div class="person-container">
    <el-card class="person-card">
      <div class="card-header">
        <h2>个人信息</h2>
      </div>
      <el-form :model="form" :rules="rules" ref="userForm" label-width="100px" class="person-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" prefix-icon="el-icon-user" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" prefix-icon="el-icon-location"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" prefix-icon="el-icon-message"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" prefix-icon="el-icon-phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save('userForm')" :loading="loading">确认修改</el-button>
          <el-button @click="resetForm('userForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Person",
  data() {
    return {
      form: {},
      loading: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadUserInfo();
  },
  methods: {
    loadUserInfo() {
      let id = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).id : null;
      if (id) {
        this.loading = true;
        this.request.get("/user/findById/" + id).then(res => {
          if (res.code === '200') {
            this.form = res.data;
          } else {
            this.$message.error('获取用户信息失败');
          }
          this.loading = false;
        }).catch(() => {
          this.loading = false;
          this.$message.error('获取用户信息失败');
        });
      } else {
        this.$message.error('未登录或登录已过期');
        this.$router.push('/login');
      }
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.request.post("/user/save", this.form).then(res => {
            if (res.code === '200') {
              this.$message.success("更新成功");
              // 更新本地存储的用户信息
              let existUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
              existUser = { ...existUser, ...this.form };
              localStorage.setItem('user', JSON.stringify(existUser));
              // 触发父组件更新
              this.$emit('refreshUser');
            } else {
              this.$message.error(res.msg || '更新失败，请联系管理员');
            }
            this.loading = false;
          }).catch(() => {
            this.loading = false;
            this.$message.error('更新失败，请稍后重试');
          });
        } else {
          this.$message.warning('请正确填写表单信息');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.loadUserInfo(); // 重新加载用户信息
    },
    handleAvatarSuccess(res, file) {
      this.form.headerUrl = res
      this.$message.success("上传成功")
      //页面传的数值动态改变，但是接受的数据不会及时显示，通过这个方法强制刷新页面解决问题
      this.$forceUpdate();
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传轮播图大小不能超过 2MB!');
      }
      return  isLt2M;
    },
    handleAvatarError(){
      this.$message.error('上传失败!');
    }
  }
}
</script>

<style scoped>
.person-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.person-card {
  max-width: 600px;
  margin: 0 auto;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.card-header {
  text-align: center;
  margin-bottom: 30px;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.person-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 25px;
}

.el-input {
  width: 100%;
}

.el-button {
  margin-right: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>